package com.ai.imagetext.service;

import com.ai.imagetext.config.AIServiceConfig;
import com.ai.imagetext.dto.AIRecognitionResult;
import com.ai.imagetext.entity.Image;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.*;

import com.aliyun.imagerecog20190930.models.TaggingImageResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.ai.imagetext.constants.Constants;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

@Slf4j
@Service
@RequiredArgsConstructor
public class AIService {
    
    private final AIServiceConfig aiConfig;
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 图像识别 - 识别图片内容并生成标签
     */
    // 创建图生标签请求
    public static com.aliyun.imagerecog20190930.Client createClient(String accessKeyId, String accessKeySecret)
            throws Exception {
        /*
         * 初始化配置对象com.aliyun.teaopenapi.models.Config
         * Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imagerecog20190930.Client(config);

    }

    public Map<String, Object> imageToTage(Image image) {
        try {
            System.out.println("================================================");
            // 从环境变量读取配置的AccessKey ID和AccessKey Secret
//            String accessKeyId = "LTAI5t7d53VD6QRsEN45Ssmg";
//            String accessKeySecret = "WpxDk7fEBu8fAKmB2uEjabST4URlOx";

            String accessKeyId = Constants.IMAGE_To_Tage_ACCESS_KEY_ID;
            String accessKeySecret = Constants.IMAGE_To_Tage_ACCESS_KEY_SECRET;

            com.aliyun.imagerecog20190930.Client client = AIService.createClient(accessKeyId, accessKeySecret);
            // 将Image转换为InputStream的几种方法：
            InputStream inputStream = convertImageToInputStream(image);
            com.aliyun.imagerecog20190930.models.TaggingImageAdvanceRequest taggingImageAdvanceRequest = new com.aliyun.imagerecog20190930.models.TaggingImageAdvanceRequest()
                    .setImageURLObject(inputStream);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                TaggingImageResponse taggingImageAdvanceResponse = client
                        .taggingImageAdvance(taggingImageAdvanceRequest, runtime);
                // 获取整体结果。
                System.out.println(
                        com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(taggingImageAdvanceResponse)));
                return TeaModel.buildMap(taggingImageAdvanceResponse);
            } catch (TeaException teaException) {
                // 获取整体报错信息。
                System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
                // 获取单个字段。
                System.out.println(teaException.getCode());
                return null;
            }
        } catch (Exception e) {
            log.error("图像标签识别失败", e);
            System.out.println("error: " + e.getMessage());
            return null;
        }
    }

    /**
     * 将Image对象转换为InputStream
     * 支持多种转换方式
     */
    private InputStream convertImageToInputStream(Image image) throws Exception {
        // 方法1：通过本地文件路径创建InputStream（推荐用于本地文件）
        if (image.getFilePath() != null && !image.getFilePath().isEmpty()) {
            File file = new File(image.getFilePath());
            if (file.exists()) {
                return new FileInputStream(file);
            }
        }

        // 方法2：通过URL创建InputStream（用于网络图片）
        if (image.getFileUrl() != null && !image.getFileUrl().isEmpty()) {
            URL url = new URL(image.getFileUrl());
            return url.openStream();
        }

        throw new IllegalArgumentException("Image对象缺少有效的文件路径或URL");
    }

    public AIRecognitionResult recognizeImage(String imageUrl) {
        log.info("Starting image recognition for URL: {}", imageUrl);
        
        if (!aiConfig.getVisionEnabled()) {
            log.warn("Vision service is disabled");
            return createDisabledResult("图像识别服务已禁用");
        }
        
        try {
            // 构建请求
            Map<String, Object> requestBody = buildVisionRequest(imageUrl);
            HttpHeaders headers = createHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            String url = aiConfig.getBaseUrl() + "services/aigc/multimodal-generation/generation";
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            
            // 解析响应
            return parseVisionResponse(response.getBody());
            
        } catch (HttpClientErrorException e) {
            log.error("Client error in image recognition: {}", e.getMessage());
            return handleClientError(e);
        } catch (HttpServerErrorException e) {
            log.error("Server error in image recognition: {}", e.getMessage());
            return handleServerError(e);
        } catch (Exception e) {
            log.error("Unexpected error in image recognition", e);
            return createErrorResult("图像识别服务暂时不可用: " + e.getMessage());
        }
    }
    
    /**
     * 构建视觉识别请求
     */
    private Map<String, Object> buildVisionRequest(String imageUrl) {
        Map<String, Object> request = new HashMap<>();
        request.put("model", aiConfig.getVisionModel());
        
        // 构建输入消息
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        
        // 构建内容数组
        List<Map<String, Object>> content = new ArrayList<>();
        
        // 添加图片
        Map<String, Object> imageContent = new HashMap<>();
        imageContent.put("type", "image_url");
        Map<String, String> imageUrl_map = new HashMap<>();
        imageUrl_map.put("url", imageUrl);
        imageContent.put("image_url", imageUrl_map);
        content.add(imageContent);
        
        // 添加文本提示
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text", buildVisionPrompt());
        content.add(textContent);
        
        message.put("content", content);
        messages.add(message);
        
        Map<String, Object> input = new HashMap<>();
        input.put("messages", messages);
        request.put("input", input);
        
        // 设置参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("result_format", "message");
        parameters.put("max_tokens", 1000);
        parameters.put("temperature", 0.1);
        request.put("parameters", parameters);
        
        return request;
    }
    
    /**
     * 构建视觉识别提示词
     */
    private String buildVisionPrompt() {
        return "请分析这张图片，并以JSON格式返回以下信息：\n" +
               "{\n" +
               "  \"description\": \"图片的详细描述\",\n" +
               "  \"tags\": [\n" +
               "    {\"name\": \"标签名称\", \"confidence\": 0.95, \"category\": \"分类\"}\n" +
               "  ],\n" +
               "  \"objects\": [\n" +
               "    {\"name\": \"对象名称\", \"confidence\": 0.90}\n" +
               "  ]\n" +
               "}\n" +
               "请确保标签准确且具有代表性，置信度在0-1之间。";
    }
    
    /**
     * 解析视觉识别响应
     */
    AIRecognitionResult parseVisionResponse(String responseBody) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            AIRecognitionResult result = new AIRecognitionResult();
            
            // 检查响应状态
            if (rootNode.has("code") && !rootNode.get("code").asText().equals("200")) {
                String errorMsg = rootNode.has("message") ? rootNode.get("message").asText() : "未知错误";
                return createErrorResult("API调用失败: " + errorMsg);
            }
            
            // 解析输出内容
            JsonNode outputNode = rootNode.path("output");
            if (outputNode.has("choices") && outputNode.get("choices").isArray() && outputNode.get("choices").size() > 0) {
                JsonNode firstChoice = outputNode.get("choices").get(0);
                JsonNode messageNode = firstChoice.path("message");
                String content = messageNode.path("content").asText();
                
                // 尝试解析JSON内容
                try {
                    JsonNode contentJson = objectMapper.readTree(content);
                    return parseRecognitionContent(contentJson, responseBody);
                } catch (Exception e) {
                    // 如果不是JSON格式，则作为描述处理
                    return createSimpleResult(content, responseBody);
                }
            }
            
            return createErrorResult("响应格式不正确");
            
        } catch (Exception e) {
            log.error("Failed to parse vision response", e);
            return createErrorResult("解析响应失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析识别内容
     */
    private AIRecognitionResult parseRecognitionContent(JsonNode contentJson, String rawResponse) {
        AIRecognitionResult result = new AIRecognitionResult();
        result.setSuccess(true);
        
        // 解析描述
        if (contentJson.has("description")) {
            result.setDescription(contentJson.get("description").asText());
        }
        
        // 解析标签
        List<AIRecognitionResult.TagInfo> tags = new ArrayList<>();
        if (contentJson.has("tags") && contentJson.get("tags").isArray()) {
            for (JsonNode tagNode : contentJson.get("tags")) {
                AIRecognitionResult.TagInfo tag = new AIRecognitionResult.TagInfo();
                tag.setName(tagNode.path("name").asText());
                tag.setConfidence(tagNode.path("confidence").asDouble(0.8));
                tag.setCategory(tagNode.path("category").asText("general"));
                tags.add(tag);
            }
        }
        result.setTags(tags);
        
        // 解析对象
        List<AIRecognitionResult.ObjectInfo> objects = new ArrayList<>();
        if (contentJson.has("objects") && contentJson.get("objects").isArray()) {
            for (JsonNode objNode : contentJson.get("objects")) {
                AIRecognitionResult.ObjectInfo obj = new AIRecognitionResult.ObjectInfo();
                obj.setName(objNode.path("name").asText());
                obj.setConfidence(objNode.path("confidence").asDouble(0.8));
                objects.add(obj);
            }
        }
        result.setObjects(objects);
        
        // 计算整体置信度
        double avgConfidence = tags.stream()
                .mapToDouble(AIRecognitionResult.TagInfo::getConfidence)
                .average()
                .orElse(0.8);
        result.setConfidence(avgConfidence);
        
        // 保存原始响应
        try {
            result.setRawResponse(objectMapper.readValue(rawResponse, Map.class));
        } catch (Exception e) {
            log.warn("Failed to parse raw response as Map", e);
        }
        
        return result;
    }
    
    /**
     * 创建简单结果（当AI返回非JSON格式时）
     */
    private AIRecognitionResult createSimpleResult(String description, String rawResponse) {
        AIRecognitionResult result = new AIRecognitionResult();
        result.setSuccess(true);
        result.setDescription(description);
        result.setConfidence(0.8);
        
        // 从描述中提取简单标签
        List<AIRecognitionResult.TagInfo> tags = extractTagsFromDescription(description);
        result.setTags(tags);
        
        result.setObjects(new ArrayList<>());
        
        try {
            result.setRawResponse(objectMapper.readValue(rawResponse, Map.class));
        } catch (Exception e) {
            log.warn("Failed to parse raw response as Map", e);
        }
        
        return result;
    }
    
    /**
     * 从描述中提取标签
     */
    private List<AIRecognitionResult.TagInfo> extractTagsFromDescription(String description) {
        List<AIRecognitionResult.TagInfo> tags = new ArrayList<>();
        
        // 简单的关键词匹配
        String[] keywords = {"食物", "饮品", "人物", "风景", "建筑", "动物", "植物", "交通工具", "电子产品", "服装"};
        
        for (String keyword : keywords) {
            if (description.contains(keyword)) {
                AIRecognitionResult.TagInfo tag = new AIRecognitionResult.TagInfo();
                tag.setName(keyword);
                tag.setConfidence(0.7);
                tag.setCategory("general");
                tags.add(tag);
            }
        }
        
        // 如果没有匹配到关键词，添加一个通用标签
        if (tags.isEmpty()) {
            AIRecognitionResult.TagInfo tag = new AIRecognitionResult.TagInfo();
            tag.setName("图片");
            tag.setConfidence(0.6);
            tag.setCategory("general");
            tags.add(tag);
        }
        
        return tags;
    }
    
    /**
     * 处理客户端错误
     */
    private AIRecognitionResult handleClientError(HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            return createErrorResult("API密钥无效或已过期");
        } else if (e.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
            return createErrorResult("API调用频率超限，请稍后重试");
        } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
            return createErrorResult("请求参数错误");
        } else {
            return createErrorResult("客户端错误: " + e.getMessage());
        }
    }
    
    /**
     * 处理服务器错误
     */
    private AIRecognitionResult handleServerError(HttpServerErrorException e) {
        return createErrorResult("AI服务暂时不可用，请稍后重试");
    }
    
    /**
     * 创建错误结果
     */
    private AIRecognitionResult createErrorResult(String errorMessage) {
        AIRecognitionResult result = new AIRecognitionResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessage);
        result.setTags(new ArrayList<>());
        result.setObjects(new ArrayList<>());
        result.setConfidence(0.0);
        return result;
    }
    
    /**
     * 创建禁用服务结果
     */
    private AIRecognitionResult createDisabledResult(String message) {
        AIRecognitionResult result = new AIRecognitionResult();
        result.setSuccess(false);
        result.setErrorMessage(message);
        result.setTags(new ArrayList<>());
        result.setObjects(new ArrayList<>());
        result.setConfidence(0.0);
        return result;
    }
    
    /**
     * 创建HTTP请求头（异步模式）
     */
    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + aiConfig.getApiKey());
        headers.set("X-DashScope-Async", "enable");
        return headers;
    }
    
    /**
     * 创建HTTP请求头（同步模式）
     */
    private HttpHeaders createSyncHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + aiConfig.getApiKey());
        return headers;
    }
    
    /**
     * 测试AI服务连接
     */
    public boolean testConnection() {
        log.info("Testing AI service connection");
        
        try {
            // 使用一个简单的测试请求
            String testImageUrl = "https://via.placeholder.com/300x200.png?text=Test";
            AIRecognitionResult result = recognizeImage(testImageUrl);
            
            boolean isConnected = result.isSuccess() || !result.getErrorMessage().contains("连接");
            log.info("AI service connection test result: {}", isConnected);
            return isConnected;
            
        } catch (Exception e) {
            log.error("AI service connection test failed", e);
            return false;
        }
    }
    
    /**
     * 文案生成 - 基于图片内容生成文案
     */
    public TextGenerationResult generateText(String imageUrl, String contentType, String styleType, String customPrompt) {
        log.info("Starting text generation for image URL: {}, type: {}, style: {}", imageUrl, contentType, styleType);
        
        if (!aiConfig.getTextGenerationEnabled()) {
            log.warn("Text generation service is disabled");
            return createDisabledTextResult("文案生成服务已禁用");
        }
        
        try {
            // 构建请求
            Map<String, Object> requestBody = buildTextGenerationRequest(imageUrl, contentType, styleType, customPrompt);
            HttpHeaders headers = createSyncHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            String url = aiConfig.getBaseUrl() + "services/aigc/multimodal-generation/generation";
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            
            // 解析响应
            return parseTextGenerationResponse(response.getBody(), contentType, styleType);
            
        } catch (HttpClientErrorException e) {
            log.error("Client error in text generation: {}", e.getMessage());
            return handleTextGenerationClientError(e);
        } catch (HttpServerErrorException e) {
            log.error("Server error in text generation: {}", e.getMessage());
            return handleTextGenerationServerError(e);
        } catch (Exception e) {
            log.error("Unexpected error in text generation", e);
            return createTextGenerationErrorResult("文案生成服务暂时不可用: " + e.getMessage());
        }
    }
    
    /**
     * 构建文案生成请求
     */
    private Map<String, Object> buildTextGenerationRequest(String imageUrl, String contentType, String styleType, String customPrompt) {
        Map<String, Object> request = new HashMap<>();
        request.put("model", aiConfig.getTextModel());
        
        // 构建输入消息
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        
        // 构建内容数组
        List<Map<String, Object>> content = new ArrayList<>();
        
        // 添加图片
        Map<String, Object> imageContent = new HashMap<>();
        imageContent.put("type", "image_url");
        Map<String, String> imageUrl_map = new HashMap<>();
        imageUrl_map.put("url", imageUrl);
        imageContent.put("image_url", imageUrl_map);
        content.add(imageContent);
        
        // 添加文本提示
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text", buildTextGenerationPrompt(contentType, styleType, customPrompt));
        content.add(textContent);
        
        message.put("content", content);
        messages.add(message);
        
        Map<String, Object> input = new HashMap<>();
        input.put("messages", messages);
        request.put("input", input);
        
        // 设置参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("result_format", "message");
        parameters.put("max_tokens", "SHORT".equals(contentType) ? 100 : 500);
        parameters.put("temperature", 0.7);
        request.put("parameters", parameters);
        
        return request;
    }
    
    /**
     * 构建文案生成提示词
     */
    private String buildTextGenerationPrompt(String contentType, String styleType, String customPrompt) {
        StringBuilder prompt = new StringBuilder();
        
        if (customPrompt != null && !customPrompt.trim().isEmpty()) {
            prompt.append(customPrompt).append("\n\n");
        }
        
        prompt.append("请根据这张图片生成");
        
        // 文案类型
        if ("SHORT".equals(contentType)) {
            prompt.append("一句简短的文案（20字以内）");
        } else {
            prompt.append("一段详细的文案（100-200字）");
        }
        
        // 文案风格
        switch (styleType) {
            case "PROMOTIONAL":
                prompt.append("，风格要求：促销营销型，具有吸引力和号召力，能够激发购买欲望");
                break;
            case "WARM":
                prompt.append("，风格要求：温暖亲切型，情感丰富，贴近生活，让人感到温馨");
                break;
            case "PROFESSIONAL":
                prompt.append("，风格要求：专业严谨型，客观描述，突出产品特点和价值");
                break;
            default:
                prompt.append("，风格自然流畅");
        }
        
        prompt.append("。请直接返回文案内容，不需要额外说明。");
        
        return prompt.toString();
    }
    
    /**
     * 解析文案生成响应
     */
    private TextGenerationResult parseTextGenerationResponse(String responseBody, String contentType, String styleType) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            TextGenerationResult result = new TextGenerationResult();
            
            // 检查响应状态
            if (rootNode.has("code") && !rootNode.get("code").asText().equals("200")) {
                String errorMsg = rootNode.has("message") ? rootNode.get("message").asText() : "未知错误";
                return createTextGenerationErrorResult("API调用失败: " + errorMsg);
            }
            
            // 解析输出内容
            JsonNode outputNode = rootNode.path("output");
            if (outputNode.has("choices") && outputNode.get("choices").isArray() && outputNode.get("choices").size() > 0) {
                JsonNode firstChoice = outputNode.get("choices").get(0);
                JsonNode messageNode = firstChoice.path("message");
                String content = messageNode.path("content").asText();
                
                result.setSuccess(true);
                result.setContent(content.trim());
                result.setContentType(contentType);
                result.setStyleType(styleType);
                
                // 保存原始响应
                try {
                    result.setRawResponse(objectMapper.readValue(responseBody, Map.class));
                } catch (Exception e) {
                    log.warn("Failed to parse raw response as Map", e);
                }
                
                return result;
            }
            
            return createTextGenerationErrorResult("响应格式不正确");
            
        } catch (Exception e) {
            log.error("Failed to parse text generation response", e);
            return createTextGenerationErrorResult("解析响应失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理文案生成客户端错误
     */
    private TextGenerationResult handleTextGenerationClientError(HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            return createTextGenerationErrorResult("API密钥无效或已过期");
        } else if (e.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
            return createTextGenerationErrorResult("API调用频率超限，请稍后重试");
        } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
            return createTextGenerationErrorResult("请求参数错误");
        } else {
            return createTextGenerationErrorResult("客户端错误: " + e.getMessage());
        }
    }
    
    /**
     * 处理文案生成服务器错误
     */
    private TextGenerationResult handleTextGenerationServerError(HttpServerErrorException e) {
        return createTextGenerationErrorResult("文案生成服务暂时不可用，请稍后重试");
    }
    
    /**
     * 创建文案生成错误结果
     */
    private TextGenerationResult createTextGenerationErrorResult(String errorMessage) {
        TextGenerationResult result = new TextGenerationResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessage);
        return result;
    }
    
    /**
     * 创建禁用文案生成结果
     */
    private TextGenerationResult createDisabledTextResult(String message) {
        TextGenerationResult result = new TextGenerationResult();
        result.setSuccess(false);
        result.setErrorMessage(message);
        return result;
    }
    
    /**
     * 获取服务状态
     */
    public Map<String, Object> getServiceStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("visionEnabled", aiConfig.getVisionEnabled());
        status.put("textGenerationEnabled", aiConfig.getTextGenerationEnabled());
        status.put("imageGenerationEnabled", aiConfig.getImageGenerationEnabled());
        status.put("baseUrl", aiConfig.getBaseUrl());
        status.put("visionModel", aiConfig.getVisionModel());
        status.put("textModel", aiConfig.getTextModel());
        status.put("imageGenerationModel", aiConfig.getImageGenerationModel());
        status.put("connectionTest", testConnection());
        return status;
    }
    
    /**
     * 图像生成 - 基于原图生成相似风格的新图片
     */
    public ImageGenerationResult generateSimilarImages(String referenceImageUrl, int count, String style, String customPrompt) {
        log.info("Starting image generation for reference URL: {}, count: {}, style: {}", referenceImageUrl, count, style);
        
        if (!aiConfig.getImageGenerationEnabled()) {
            log.warn("Image generation service is disabled");
            return createDisabledImageResult("图像生成服务已禁用");
        }
        
        try {
            // 构建请求
            Map<String, Object> requestBody = buildImageGenerationRequest(referenceImageUrl, count, style, customPrompt);
            HttpHeaders headers = createHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            String url = aiConfig.getBaseUrl() + "services/aigc/text2image/image-synthesis";
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            
            // 解析响应
            return parseImageGenerationResponse(response.getBody(), referenceImageUrl, count, style);
            
        } catch (HttpClientErrorException e) {
            log.error("Client error in image generation: {}", e.getMessage());
            return handleImageGenerationClientError(e);
        } catch (HttpServerErrorException e) {
            log.error("Server error in image generation: {}", e.getMessage());
            return handleImageGenerationServerError(e);
        } catch (Exception e) {
            log.error("Unexpected error in image generation", e);
            return createImageGenerationErrorResult("图像生成服务暂时不可用: " + e.getMessage());
        }
    }
    
    /**
     * 构建图像生成请求
     */
    private Map<String, Object> buildImageGenerationRequest(String referenceImageUrl, int count, String style, String customPrompt) {
        Map<String, Object> request = new HashMap<>();
        request.put("model", aiConfig.getImageGenerationModel());
        
        // 构建输入
        Map<String, Object> input = new HashMap<>();
        
        // 构建提示词
        String prompt = buildImageGenerationPrompt(referenceImageUrl, style, customPrompt);
        input.put("prompt", prompt);
        
        // 添加参考图片
        if (referenceImageUrl != null && !referenceImageUrl.isEmpty()) {
            input.put("ref_img", referenceImageUrl);
        }
        
        request.put("input", input);
        
        // 设置参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("style", style != null ? style : "auto");
        parameters.put("size", "1024*1024");
        parameters.put("n", Math.min(count, 4)); // 限制最多4张
        parameters.put("seed", (int) (Math.random() * 1000000));
        request.put("parameters", parameters);
        
        return request;
    }
    
    /**
     * 构建图像生成提示词
     */
    private String buildImageGenerationPrompt(String referenceImageUrl, String style, String customPrompt) {
        StringBuilder prompt = new StringBuilder();
        
        if (customPrompt != null && !customPrompt.trim().isEmpty()) {
            prompt.append(customPrompt).append(", ");
        }
        
        prompt.append("generate a similar image with the same style and theme");
        
        // 根据风格添加描述
        switch (style != null ? style.toLowerCase() : "auto") {
            case "product":
                prompt.append(", product photography style, clean background, professional lighting");
                break;
            case "lifestyle":
                prompt.append(", lifestyle photography, natural setting, warm atmosphere");
                break;
            case "artistic":
                prompt.append(", artistic style, creative composition, enhanced colors");
                break;
            case "minimalist":
                prompt.append(", minimalist style, simple composition, clean design");
                break;
            default:
                prompt.append(", maintain original style and mood");
        }
        
        prompt.append(", high quality, detailed");
        
        return prompt.toString();
    }
    
    /**
     * 解析图像生成响应
     */
    private ImageGenerationResult parseImageGenerationResponse(String responseBody, String referenceImageUrl, int count, String style) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            ImageGenerationResult result = new ImageGenerationResult();
            
            // 检查响应状态
            if (rootNode.has("code") && !rootNode.get("code").asText().equals("200")) {
                String errorMsg = rootNode.has("message") ? rootNode.get("message").asText() : "未知错误";
                return createImageGenerationErrorResult("API调用失败: " + errorMsg);
            }
            
            // 解析输出内容
            JsonNode outputNode = rootNode.path("output");
            if (outputNode.has("results") && outputNode.get("results").isArray()) {
                List<String> imageUrls = new ArrayList<>();
                
                for (JsonNode resultNode : outputNode.get("results")) {
                    if (resultNode.has("url")) {
                        imageUrls.add(resultNode.get("url").asText());
                    }
                }
                
                result.setSuccess(true);
                result.setGeneratedImageUrls(imageUrls);
                result.setReferenceImageUrl(referenceImageUrl);
                result.setRequestedCount(count);
                result.setActualCount(imageUrls.size());
                result.setStyle(style);
                
                // 保存原始响应
                try {
                    result.setRawResponse(objectMapper.readValue(responseBody, Map.class));
                } catch (Exception e) {
                    log.warn("Failed to parse raw response as Map", e);
                }
                
                return result;
            }
            
            return createImageGenerationErrorResult("响应格式不正确");
            
        } catch (Exception e) {
            log.error("Failed to parse image generation response", e);
            return createImageGenerationErrorResult("解析响应失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理图像生成客户端错误
     */
    private ImageGenerationResult handleImageGenerationClientError(HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            return createImageGenerationErrorResult("API密钥无效或已过期");
        } else if (e.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
            return createImageGenerationErrorResult("API调用频率超限，请稍后重试");
        } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
            return createImageGenerationErrorResult("请求参数错误");
        } else {
            return createImageGenerationErrorResult("客户端错误: " + e.getMessage());
        }
    }
    
    /**
     * 处理图像生成服务器错误
     */
    private ImageGenerationResult handleImageGenerationServerError(HttpServerErrorException e) {
        return createImageGenerationErrorResult("图像生成服务暂时不可用，请稍后重试");
    }
    
    /**
     * 创建图像生成错误结果
     */
    private ImageGenerationResult createImageGenerationErrorResult(String errorMessage) {
        ImageGenerationResult result = new ImageGenerationResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessage);
        result.setGeneratedImageUrls(new ArrayList<>());
        return result;
    }
    
    /**
     * 创建禁用图像生成结果
     */
    private ImageGenerationResult createDisabledImageResult(String message) {
        ImageGenerationResult result = new ImageGenerationResult();
        result.setSuccess(false);
        result.setErrorMessage(message);
        result.setGeneratedImageUrls(new ArrayList<>());
        return result;
    }
    
    /**
     * 文案生成结果类
     */
    public static class TextGenerationResult {
        private boolean success;
        private String errorMessage;
        private String content;
        private String contentType;
        private String styleType;
        private Map<String, Object> rawResponse;
        
        // Getters and Setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getContentType() { return contentType; }
        public void setContentType(String contentType) { this.contentType = contentType; }
        
        public String getStyleType() { return styleType; }
        public void setStyleType(String styleType) { this.styleType = styleType; }
        
        public Map<String, Object> getRawResponse() { return rawResponse; }
        public void setRawResponse(Map<String, Object> rawResponse) { this.rawResponse = rawResponse; }
    }
    
    /**
     * 图像生成结果类
     */
    public static class ImageGenerationResult {
        private boolean success;
        private String errorMessage;
        private List<String> generatedImageUrls;
        private String referenceImageUrl;
        private int requestedCount;
        private int actualCount;
        private String style;
        private Map<String, Object> rawResponse;
        
        // Getters and Setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        
        public List<String> getGeneratedImageUrls() { return generatedImageUrls; }
        public void setGeneratedImageUrls(List<String> generatedImageUrls) { this.generatedImageUrls = generatedImageUrls; }
        
        public String getReferenceImageUrl() { return referenceImageUrl; }
        public void setReferenceImageUrl(String referenceImageUrl) { this.referenceImageUrl = referenceImageUrl; }
        
        public int getRequestedCount() { return requestedCount; }
        public void setRequestedCount(int requestedCount) { this.requestedCount = requestedCount; }
        
        public int getActualCount() { return actualCount; }
        public void setActualCount(int actualCount) { this.actualCount = actualCount; }
        
        public String getStyle() { return style; }
        public void setStyle(String style) { this.style = style; }
        
        public Map<String, Object> getRawResponse() { return rawResponse; }
        public void setRawResponse(Map<String, Object> rawResponse) { this.rawResponse = rawResponse; }
    }
}
